package com.gqh.weather.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gqh.weather.domain.dto.ScoreTeacherAccountConfig;
import com.gqh.weather.domain.dto.YjStInfo;
import com.gqh.weather.domain.dto.YuejuanExamInfoResponse;
import com.gqh.weather.domain.dto.TaskSchedule;
import com.gqh.weather.domain.dto.PaperInfo;
import com.gqh.weather.domain.dto.YjStScoreRecord;
import com.gqh.weather.domain.dto.YuejuanStudentAnswer;
import com.gqh.weather.domain.dto.StudentUploadAnswerData;
import com.gqh.weather.domain.dto.YuejuanScore;
import com.gqh.weather.domain.entity.PcSubtask;
import com.gqh.weather.domain.entity.Question;
import com.gqh.weather.domain.entity.Task;
import com.gqh.weather.domain.entity.Paper;
import com.gqh.weather.domain.entity.YjStudentAnswerScore;
import com.gqh.weather.domain.entity.StudentAnswer;
import com.gqh.weather.exception.BusinessException;
import com.gqh.weather.mapper.PcSubtaskMapper;
import com.gqh.weather.mapper.QuestionMapper;
import com.gqh.weather.mapper.TaskMapper;
import com.gqh.weather.mapper.PaperMapper;
import com.gqh.weather.mapper.StudentAnswerMapper;
import com.gqh.weather.mapper.YjStudentAnswerScoreMapper;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.stream.Collectors;

import java.time.Instant;
import com.fasterxml.jackson.core.type.TypeReference;

/**
 * 阅卷平台服务类
 */
@Slf4j
@Service
public class YuejuanService extends ServiceImpl<PcSubtaskMapper, PcSubtask> {
    
    @Autowired
    private PcSubtaskMapper pcSubtaskMapper;
    
    @Autowired
    private TaskMapper taskMapper;
    
    @Autowired
    private QuestionMapper questionMapper;
    
    @Autowired
    private PaperMapper paperMapper;

    @Autowired
    private PaperService paperService;
    
    @Autowired
    private YjStudentAnswerScoreMapper yjStudentAnswerScoreMapper;
    
    @Autowired
    private StudentAnswerMapper studentAnswerMapper;
    
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 阅卷老师登录验证
     *
     * @param account 账号
     * @param password 密码
     * @param role 角色：0正评 1复评 2仲裁
     * @return 题目ID和子任务信息
     */
    public YuejuanLoginResult login(String account, String password, String role) {
        try {
            // 构造查询条件，查找匹配的子任务
            // 模拟Go代码中的LIKE查询: a.score_teacher LIKE '%{"acc":"account","pwd":"password"}%'
            String accData = String.format("%%\"acc\":\"%s\",\"pwd\":%s%%", account, password);
            
            LambdaQueryWrapper<PcSubtask> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(PcSubtask::getScoreTeacher, accData)
                   .eq(PcSubtask::getIsDeleted, 0)
                   .orderByDesc(PcSubtask::getId);
            
            PcSubtask subtaskInfo = pcSubtaskMapper.selectOne(wrapper);
            if (subtaskInfo == null) {
                throw new BusinessException("账号或密码不正确");
            }
            
            // 检查任务状态
            if (subtaskInfo.getState() == 0) {
                throw new BusinessException("考务未发布");
            }
            
            if (subtaskInfo.getState() == 2) {
                throw new BusinessException("考务已结束");
            }
            
            // 检查阅卷时间是否过期
            Task taskInfo = taskMapper.selectById(subtaskInfo.getTaskPid());
            if (taskInfo == null) {
                throw new BusinessException("关联任务不存在");
            }
            
            if (taskInfo.getEndAt() != null && 
                taskInfo.getEndAt() < Instant.now().getEpochSecond()) {
                throw new BusinessException("阅卷工作已过期！");
            }
            
            // 检查阅卷模式
            if (subtaskInfo.getType() == 0) {
                throw new BusinessException("考试任务阅卷模式为不阅卷");
            }
            
            // 根据角色检查权限
            int roleInt = Integer.parseInt(role);
            if (subtaskInfo.getZfPing() == 0 && roleInt == 1) {
                throw new BusinessException("考试任务只有正评，无法登录复评账号");
            }
            
            if (subtaskInfo.getDsPing() == 0 && roleInt == 2) {
                throw new BusinessException("考试任务为单评，无法登录仲裁账号");
            }
            
            // 检查阅卷状态
            if (subtaskInfo.getYjState() == 0) {
                throw new BusinessException("阅卷工作未开始！");
            }
            
            if (subtaskInfo.getYjState() == 2) {
                throw new BusinessException("阅卷工作已结束！");
            }
            
            // 检查复评状态
            if (roleInt == 1 && subtaskInfo.getFpState() == 0) {
                throw new BusinessException("复评工作未开始！");
            }
            
            if ((roleInt == 0 || roleInt == 2) && subtaskInfo.getFpState() == 1) {
                throw new BusinessException("正评工作已结束！");
            }
            
            // 验证账号密码与角色匹配
            int qId = validateAccountAndPassword(subtaskInfo, account, password, roleInt);
            
            return new YuejuanLoginResult(qId, subtaskInfo);
            
        } catch (BusinessException e) {
            throw e; // 重新抛出业务异常
        } catch (Exception e) {
            log.error("登录验证失败", e);
            throw new BusinessException("登录验证失败: " + e.getMessage());
        }
    }
    
    /**
     * 验证账号密码与角色匹配
     *
     * @param subtaskInfo 子任务信息
     * @param account 账号
     * @param password 密码
     * @param role 角色
     * @return 题目ID
     */
    private int validateAccountAndPassword(PcSubtask subtaskInfo, String account, String password, int role) {
        try {
            // 解析score_teacher字段中的账号信息
            String scoreTeacherData = subtaskInfo.getScoreTeacher();
            if (scoreTeacherData == null || scoreTeacherData.isEmpty()) {
                throw new BusinessException("账号信息不存在");
            }
            
            // 解析score_teacher JSON数据
            ScoreTeacherAccountConfig stCfg = objectMapper.readValue(scoreTeacherData, ScoreTeacherAccountConfig.class);
            
            // 根据角色获取对应的账号列表
            Map<String, List<ScoreTeacherAccountConfig.ScoreTeacherAccount>> accountsMap = null;
            switch (role) {
                case 0: // 正评
                    accountsMap = stCfg.getStart();
                    break;
                case 1: // 复评
                    accountsMap = stCfg.getReview();
                    break;
                case 2: // 仲裁
                    accountsMap = stCfg.getEnd();
                    break;
                default:
                    throw new BusinessException("role参数不正确");
            }
            
            if (accountsMap == null) {
                throw new BusinessException("角色配置不存在");
            }
            
            // 遍历账号列表，验证账号密码
            boolean roleValid = false;
            int qId = 0;
            
            for (Map.Entry<String, List<ScoreTeacherAccountConfig.ScoreTeacherAccount>> entry : accountsMap.entrySet()) {
                String qidStr = entry.getKey();
                List<ScoreTeacherAccountConfig.ScoreTeacherAccount> accountList = entry.getValue();
                
                // 遍历该题目的账号列表
                for (ScoreTeacherAccountConfig.ScoreTeacherAccount stAccount : accountList) {
                    if (stAccount.getAcc().equals(account) && stAccount.getPwd().toString().equals(password)) {
                        roleValid = true;
                        qId = Integer.parseInt(qidStr);
                        break;
                    }
                }
                
                if (roleValid) {
                    break;
                }
            }
            
            if (!roleValid) {
                throw new BusinessException("账号密码与账号类型不匹配");
            }
            
            return qId;
            
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("账号密码验证失败", e);
            throw new BusinessException("账号密码验证失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取考试详情
     *
     * @param stInfo 阅卷老师信息
     * @return 考试信息
     */
    public YuejuanExamInfoResponse examInfo(YjStInfo stInfo) {
        try {
            // 获取子任务信息
            PcSubtask subtaskInfo = pcSubtaskMapper.selectById(stInfo.getSubtaskId());
            if (subtaskInfo == null) {
                throw new BusinessException("子任务不存在");
            }
            
            // 获取任务信息
            Task taskInfo = taskMapper.selectById(subtaskInfo.getTaskPid());
            if (taskInfo == null) {
                throw new BusinessException("关联任务不存在");
            }
            
            // 获取题目信息
            Question qInfo = questionMapper.selectById(stInfo.getQid());
            if (qInfo == null) {
                throw new BusinessException("题目不存在");
            }
            
            // 获取题目分数
            List<TaskSchedule> taskSchedule = objectMapper.readValue(subtaskInfo.getSchedule(), new TypeReference<List<TaskSchedule>>() {});
            int questionScore = 0;
            String questionSingleScore = "";
            
            for (TaskSchedule ts : taskSchedule) {
                int paperType = Integer.parseInt(ts.getType());
                if (paperType == qInfo.getType()) {
                    // Paper paper = paperMapper.selectById(ts.getPaperId());
                    PaperInfo paperInfo = paperService.getPaperInfo(ts.getPaperId()).getData();
                    if (paperInfo != null && paperInfo.getDataInfo() != null) {
                        for (PaperInfo.PaperInfoData pdi : paperInfo.getDataInfo()) {
                            if (pdi.getQinfos() != null) {
                                for (PaperInfo.QuestionInfos qi : pdi.getQinfos()) {
                                    if (qi.getId() == stInfo.getQid()) {
                                        questionScore = pdi.getScore();
                                        questionSingleScore = pdi.getSingleScore();
                                        break;
                                    }
                                }
                                if (!questionSingleScore.isEmpty()) {
                                    break;
                                }
                            }
                        }
                        if (!questionSingleScore.isEmpty()) {
                            break;
                        }
                    }
                }
            }
            
            if (questionSingleScore.isEmpty()) {
                throw new BusinessException("试卷题目不存在");
            }
            
            YuejuanExamInfoResponse res = null;
            
            if (stInfo.getRole() == 0) {
                // 正评
                res = zpExamInfo(taskInfo.getCreatedBy(), stInfo, subtaskInfo, qInfo);
            } else if (stInfo.getRole() == 1) {
                // 复评
                res = fpExamInfo(taskInfo.getCreatedBy(), stInfo, subtaskInfo, qInfo);
            } else if (stInfo.getRole() == 2) {
                // 仲裁
                double qScore = Double.parseDouble(questionSingleScore);
                res = zcExamInfo(taskInfo.getCreatedBy(), qScore, stInfo, subtaskInfo, qInfo);
            }
            
            if (res != null) {
                res.setRole(stInfo.getRole());
                res.setQuestionScore(questionScore);
                res.setQuestionSingleScore(questionSingleScore);
            }
            
            return res;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("获取考试详情失败", e);
            throw new BusinessException("获取考试详情失败: " + e.getMessage());
        }
    }
    
    /**
     * 正评考试信息
     *
     * @param uid 用户ID
     * @param stInfo 阅卷老师信息
     * @param subtaskInfo 子任务信息
     * @param qInfo 题目信息
     * @return 考试信息响应
     */
    private YuejuanExamInfoResponse zpExamInfo(Integer uid, YjStInfo stInfo, PcSubtask subtaskInfo, Question qInfo) {
        YuejuanExamInfoResponse res = new YuejuanExamInfoResponse();
        res.setQuestionInfo(qInfo);
        res.setYjStudentInfo(new ArrayList<>());
        
        // 解析阅卷老师账号
        try {
            ScoreTeacherAccountConfig stCfg = objectMapper.readValue(subtaskInfo.getScoreTeacher(), ScoreTeacherAccountConfig.class);
            
            // 获取阅卷老师总数
            int stCount = 0;
            int stIdx = 0;
            
            if (stCfg.getStart() != null) {
                for (Map.Entry<String, List<ScoreTeacherAccountConfig.ScoreTeacherAccount>> entry : stCfg.getStart().entrySet()) {
                    int iqid = Integer.parseInt(entry.getKey());
                    if (iqid == stInfo.getQid()) {
                        stCount = entry.getValue().size();
                        for (int idx = 0; idx < entry.getValue().size(); idx++) {
                            ScoreTeacherAccountConfig.ScoreTeacherAccount stAccount = entry.getValue().get(idx);
                            if (stAccount.getAcc().equals(stInfo.getAccount())) {
                                stIdx = idx;
                                break;
                            }
                        }
                        break;
                    }
                }
            }
            
            // 获取学生的答案
            List<StudentAnswer> stuAnsList = studentAnswerMapper.selectByTaskIdAndPaperTypeAndStudentIds(
                subtaskInfo.getTaskPid(), qInfo.getType(), null);
            
            if (stuAnsList.isEmpty()) {
                return res;
            }
            
            List<Integer> stuList = new ArrayList<>();
            Map<Integer, String> stuAnsMap = new HashMap<>();
            
            for (StudentAnswer stuAns : stuAnsList) {
                if (!stuList.contains(stuAns.getStudentId())) {
                    stuList.add(stuAns.getStudentId());
                }
                
                // 解析scoreData字段获取答案
                try {
                    List<StudentUploadAnswerData> scoreDataList = objectMapper.readValue(
                        stuAns.getAnswer(), 
                        new TypeReference<List<StudentUploadAnswerData>>() {});
                    
                    // 查找对应题目的答案
                    for (StudentUploadAnswerData data : scoreDataList) {
                        if (data.getQid().equals(stInfo.getQid())) {
                            stuAnsMap.put(stuAns.getStudentId(), data.getAnswer());
                            break;
                        }
                    }
                } catch (Exception e) {
                    log.warn("解析学生答案失败, studentId: {}", stuAns.getStudentId(), e);
                }
            }
            
            // 计算分配给当前老师的学生列表
            int stuCount = stuList.size();
            List<Integer> stuIdList = new ArrayList<>();
            
            if (subtaskInfo.getDsPing() == 1) {
                // 双评 按账号数除2 平分学生 (1/2,3/4)成对分配相同任务
                int avgCount = stuCount / (stCount / 2);
                int yCount = stuCount % (stCount / 2);
                int page = stIdx / 2;
                int preOffset = 0;
                
                if ((yCount > 0) && (page < yCount)) {
                    avgCount += 1;
                }
                
                if (yCount > 0 && page > 0) {
                    if (page < yCount) {
                        preOffset = page;
                    } else {
                        preOffset = yCount;
                    }
                }
                
                int offset = avgCount * page + preOffset;
                for (int i = 0; i < avgCount && (i + offset) < stuList.size(); i++) {
                    stuIdList.add(stuList.get(i + offset));
                }
            } else {
                // 单评 按账号数 平分学生
                int avgCount = stuCount / stCount;
                int yCount = stuCount % stCount;
                int page = stIdx;
                
                if ((yCount > 0) && (page < yCount)) {
                    avgCount += 1;
                }
                
                int preOffset = 0;
                if (yCount > 0 && page > 0) {
                    if (page < yCount) {
                        preOffset = page;
                    } else {
                        preOffset = yCount;
                    }
                }
                
                int offset = avgCount * page + preOffset;
                for (int i = 0; i < avgCount && (i + offset) < stuList.size(); i++) {
                    stuIdList.add(stuList.get(i + offset));
                }
            }
            
            // 获取学生的评分记录
            List<YjStudentAnswerScore> yjsaList = yjStudentAnswerScoreMapper.selectByStudentIdsAndQidAndRole(
                stuIdList, stInfo.getQid(), 0, stInfo.getAccount());
            
            Map<Integer, YjStudentAnswerScore> yjsaMap = new HashMap<>();
            for (YjStudentAnswerScore yjsa : yjsaList) {
                yjsaMap.put(yjsa.getStudentId(), yjsa);
            }
            
            // 构建返回结果
            List<YuejuanStudentAnswer> yjStudentInfo = new ArrayList<>();
            for (Integer stuId : stuIdList) {
                // 获取打分记录
                YjStudentAnswerScore yjsaRec = yjsaMap.get(stuId);
                Double yjsaScore = 0.0;
                String ifRead = "";
                
                if (yjsaRec != null) {
                    yjsaScore = yjsaRec.getScore();
                    ifRead = yjsaRec.getIfRead();
                }
                
                YuejuanStudentAnswer yjsa = new YuejuanStudentAnswer();
                yjsa.setStudentId(stuId);
                yjsa.setTaskId(subtaskInfo.getTaskPid());
                yjsa.setPcSubtaskId(subtaskInfo.getId());
                yjsa.setQid(stInfo.getQid());
                yjsa.setPaperType(qInfo.getType());
                yjsa.setAnswer(stuAnsMap.getOrDefault(stuId, ""));
                yjsa.setScore(yjsaScore);
                yjsa.setIfRead(ifRead);
                yjStudentInfo.add(yjsa);
            }
            
            res.setYjStudentInfo(yjStudentInfo);
            
        } catch (Exception e) {
            log.error("解析阅卷老师账号失败", e);
        }
        
        return res;
    }
    
    /**
     * 复评考试信息
     *
     * @param uid 用户ID
     * @param stInfo 阅卷老师信息
     * @param subtaskInfo 子任务信息
     * @param qInfo 题目信息
     * @return 考试信息响应
     */
    private YuejuanExamInfoResponse fpExamInfo(Integer uid, YjStInfo stInfo, PcSubtask subtaskInfo, Question qInfo) {
        YuejuanExamInfoResponse res = new YuejuanExamInfoResponse();
        res.setQuestionInfo(qInfo);
        res.setYjStudentInfo(new ArrayList<>());
        
        if (subtaskInfo.getZfPing() == 0) {
            // 只有正评
            return res;
        }
        
        // 获取学生的答案
        List<StudentAnswer> stuAnsList = studentAnswerMapper.selectByTaskIdAndPaperTypeAndStudentIds(
            subtaskInfo.getTaskPid(), qInfo.getType(), null);
        
        if (stuAnsList.isEmpty()) {
            return res;
        }
        
        List<Integer> stuList = new ArrayList<>();
        Map<Integer, String> stuAnsMap = new HashMap<>();
        
        for (StudentAnswer stuAns : stuAnsList) {
            if (!stuList.contains(stuAns.getStudentId())) {
                stuList.add(stuAns.getStudentId());
            }
            
            // 解析scoreData字段获取答案
            try {
                List<StudentUploadAnswerData> scoreDataList = objectMapper.readValue(
                    stuAns.getAnswer(), 
                    new TypeReference<List<StudentUploadAnswerData>>() {});
                
                // 查找对应题目的答案
                for (StudentUploadAnswerData data : scoreDataList) {
                    if (data.getQid().equals(stInfo.getQid())) {
                        stuAnsMap.put(stuAns.getStudentId(), data.getAnswer());
                        break;
                    }
                }
            } catch (Exception e) {
                log.warn("解析学生答案失败, studentId: {}", stuAns.getStudentId(), e);
            }
        }
        
        // 抽取10%的学生
        double percent = 0.1;
        int sampleSize = (int) (stuList.size() * percent);
        if (sampleSize == 0) {
            sampleSize = 1; // 切片长度太小
        }
        
        // 随机抽取学生ID
        Collections.shuffle(stuList);
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < Math.min(sampleSize, stuList.size()); i++) {
            result.add(stuList.get(i));
        }
        
        // 获取学生的评分记录
        List<YjStudentAnswerScore> yjsaList = yjStudentAnswerScoreMapper.selectByStudentIdsAndQidAndRole(
            result, stInfo.getQid(), 1, stInfo.getAccount());
        
        Map<Integer, YjStudentAnswerScore> yjsaMap = new HashMap<>();
        for (YjStudentAnswerScore yjsa : yjsaList) {
            yjsaMap.put(yjsa.getStudentId(), yjsa);
        }
        
        // 构建返回结果
        List<YuejuanStudentAnswer> yjStudentInfo = new ArrayList<>();
        for (Integer stuId : result) {
            // 获取打分记录
            YjStudentAnswerScore yjsaRec = yjsaMap.get(stuId);
            Double yjsaScore = 0.0;
            String ifRead = "";
            
            if (yjsaRec != null) {
                yjsaScore = yjsaRec.getScore();
                ifRead = yjsaRec.getIfRead();
            }
            
            YuejuanStudentAnswer yjsa = new YuejuanStudentAnswer();
            yjsa.setStudentId(stuId);
            yjsa.setTaskId(subtaskInfo.getTaskPid());
            yjsa.setPcSubtaskId(subtaskInfo.getId());
            yjsa.setQid(stInfo.getQid());
            yjsa.setPaperType(qInfo.getType());
            yjsa.setAnswer(stuAnsMap.getOrDefault(stuId, ""));
            yjsa.setScore(yjsaScore);
            yjsa.setIfRead(ifRead);
            yjStudentInfo.add(yjsa);
        }
        
        res.setYjStudentInfo(yjStudentInfo);
        
        return res;
    }
    
    /**
     * 仲裁考试信息
     *
     * @param uid 用户ID
     * @param score 题目分数
     * @param stInfo 阅卷老师信息
     * @param subtaskInfo 子任务信息
     * @param qInfo 题目信息
     * @return 考试信息响应
     */
    private YuejuanExamInfoResponse zcExamInfo(Integer uid, double score, YjStInfo stInfo, PcSubtask subtaskInfo, Question qInfo) {
        YuejuanExamInfoResponse res = new YuejuanExamInfoResponse();
        res.setQuestionInfo(qInfo);
        res.setYjStudentInfo(new ArrayList<>());
        
        if (subtaskInfo.getDsPing() == 0) {
            // 单评
            return res;
        }
        
        // 获取所有评分记录
        List<YjStudentAnswerScore> stuScoreList = yjStudentAnswerScoreMapper.selectByTaskIdAndPaperTypeAndQid(
            subtaskInfo.getTaskPid(), qInfo.getType(), stInfo.getQid());
        
        // 构建学生评分映射
        Map<Integer, List<YjStudentAnswerScore>> stuScoreMap = new HashMap<>();
        for (YjStudentAnswerScore s : stuScoreList) {
            stuScoreMap.computeIfAbsent(s.getStudentId(), k -> new ArrayList<>()).add(s);
        }
        
        List<Integer> stuIdList = new ArrayList<>();
        Map<Integer, YjStScoreRecord> stScoreRecordMap = new HashMap<>();
        
        for (Map.Entry<Integer, List<YjStudentAnswerScore>> entry : stuScoreMap.entrySet()) {
            Integer stuId = entry.getKey();
            List<YjStudentAnswerScore> scores = entry.getValue();
            
            if (scores.size() != 2) {
                // 已经复评或仲裁的不返回
                continue;
            }
            
            if (scores.get(0).getStRole().equals(scores.get(1).getStRole())) {
                // 已经复评或仲裁
                continue;
            }
            
            double diffScore = 0;
            double score1 = scores.get(0).getScore();
            double score2 = scores.get(1).getScore();
            
            if (score1 < score2) {
                diffScore = score2 - score1;
            } else {
                diffScore = score1 - score2;
            }
            
            // 分数差异超过题分的50%需要仲裁
            if (score / 2 < diffScore) {
                stuIdList.add(stuId);
                YjStScoreRecord record = new YjStScoreRecord();
                record.setAccount1(scores.get(0).getTeacherAccount());
                record.setScore1(score1);
                record.setAccount2(scores.get(1).getTeacherAccount());
                record.setScore2(score2);
                stScoreRecordMap.put(stuId, record);
            }
        }
        
        // 获取学生的答案
        if (!stuIdList.isEmpty()) {
            List<StudentAnswer> stuAnsList = studentAnswerMapper.selectByTaskIdAndPaperTypeAndStudentIds(
                subtaskInfo.getTaskPid(), qInfo.getType(), stuIdList);
            
            // 构建学生答案映射
            Map<Integer, String> stuAnsMap = new HashMap<>();
            for (StudentAnswer stuAns : stuAnsList) {
                // 解析scoreData字段获取答案
                try {
                    List<StudentUploadAnswerData> scoreDataList = objectMapper.readValue(
                        stuAns.getAnswer(), 
                        new TypeReference<List<StudentUploadAnswerData>>() {});
                    
                    // 查找对应题目的答案
                    for (StudentUploadAnswerData data : scoreDataList) {
                        if (data.getQid().equals(stInfo.getQid())) {
                            stuAnsMap.put(stuAns.getStudentId(), data.getAnswer());
                            break;
                        }
                    }
                } catch (Exception e) {
                    log.warn("解析学生答案失败, studentId: {}", stuAns.getStudentId(), e);
                }
            }
            
            // 构建返回结果
            List<YuejuanStudentAnswer> yjStudentInfo = new ArrayList<>();
            for (Integer stuId : stuIdList) {
                YuejuanStudentAnswer yjsa = new YuejuanStudentAnswer();
                yjsa.setStudentId(stuId);
                yjsa.setTaskId(subtaskInfo.getTaskPid());
                yjsa.setPcSubtaskId(subtaskInfo.getId());
                yjsa.setQid(stInfo.getQid());
                yjsa.setPaperType(qInfo.getType());
                yjsa.setAnswer(stuAnsMap.getOrDefault(stuId, ""));
                yjsa.setStScores(stScoreRecordMap.get(stuId));
                yjStudentInfo.add(yjsa);
            }
            res.setYjStudentInfo(yjStudentInfo);
        }
        
        return res;
    }
    
    /**
     * 登录结果封装类
     */
    public static class YuejuanLoginResult {
        private int qId;
        private PcSubtask subtaskInfo;
        
        public YuejuanLoginResult(int qId, PcSubtask subtaskInfo) {
            this.qId = qId;
            this.subtaskInfo = subtaskInfo;
        }
        
        public int getQId() {
            return qId;
        }
        
        public PcSubtask getSubtaskInfo() {
            return subtaskInfo;
        }
    }
    
    /**
     * 打分提交
     *
     * @param subtaskId 子任务ID
     * @param qid 题目ID
     * @param role 角色
     * @param stAcc 老师账号
     * @param score 打分信息
     * @throws BusinessException 业务异常
     */
    public void score(Integer subtaskId, Integer qid, Integer role, String stAcc, YuejuanScore score) throws BusinessException {
        try {
            if (score.getStudentId() == null || score.getStudentId() == 0) {
                throw new BusinessException("student_id参数不正确");
            }
            
            // 获取子任务信息
            PcSubtask subtaskInfo = pcSubtaskMapper.selectById(subtaskId);
            if (subtaskInfo == null) {
                throw new BusinessException("子任务不存在");
            }
            
            // 检查任务状态
            if (subtaskInfo.getState() != null && subtaskInfo.getState() == 2) {
                throw new BusinessException("考评已经结束");
            }
            
            // 获取任务信息
            Task taskInfo = taskMapper.selectById(subtaskInfo.getTaskPid());
            if (taskInfo == null) {
                throw new BusinessException("关联任务不存在");
            }
            
            // 获取题目信息
            Question qInfo = questionMapper.selectById(qid);
            if (qInfo == null) {
                throw new BusinessException("题目不存在");
            }
            
            // 检查学生答题记录
            List<StudentAnswer> saList = studentAnswerMapper.selectByTaskIdAndPaperTypeAndStudentIds(
                taskInfo.getId(), qInfo.getType(), Arrays.asList(score.getStudentId()));
            if (saList.isEmpty()) {
                throw new BusinessException("没有该学生的答题记录");
            }
            
            // 获取评分记录
            List<YjStudentAnswerScore> yjList = yjStudentAnswerScoreMapper.selectByStudentIdAndQidAndRole(
                score.getStudentId(), qid, role, stAcc);
            
            if (yjList.isEmpty()) {
                // 新建记录
                YjStudentAnswerScore newScore = new YjStudentAnswerScore();
                newScore.setStudentId(score.getStudentId());
                newScore.setTaskId(subtaskInfo.getTaskPid());
                newScore.setPaperType(qInfo.getType());
                newScore.setQid(qid);
                newScore.setScore(Double.parseDouble(score.getScore()));
                newScore.setTeacherAccount(stAcc);
                newScore.setStRole(role);
                newScore.setIfRead("1");
                newScore.setStudentAnswerId(0);
                yjStudentAnswerScoreMapper.insert(newScore);
            } else {
                // 更新记录
                YjStudentAnswerScore existingScore = yjList.get(0);
                if (!score.getScore().equals(String.valueOf(existingScore.getScore()))) {
                    existingScore.setScore(Double.parseDouble(score.getScore()));
                    yjStudentAnswerScoreMapper.updateById(existingScore);
                }
            }
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("打分提交失败", e);
            throw new BusinessException("打分提交失败: " + e.getMessage());
        }
    }
}